package com.zhifuliu;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;

// 1. 设计员工类
class Employee implements Serializable {
    private final String name;
    private final int age;
    private final double salary;

    public Employee(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "员工姓名：" + name + "，年龄：" + age + "，薪资：" + salary;
    }
}

public class EmployeeFileIO {
    public static void main(String[] args) {
        // 2. 创建三个员工对象
        Employee emp1 = new Employee("张三", 25, 5000.0);
        Employee emp2 = new Employee("李四", 30, 8000.0);
        Employee emp3 = new Employee("王五", 28, 6500.0);

        // 将员工对象添加到集合
        ArrayList<Employee> employees = new ArrayList<>();
        employees.add(emp1);
        employees.add(emp2);
        employees.add(emp3);

        // 文件路径（可根据需要修改）
        String filePath = "employees.dat";

        try {
            // 3. 将员工信息写入文件
            ObjectOutputStream oos = new ObjectOutputStream(
                    Files.newOutputStream(Paths.get(filePath)));
            oos.writeObject(employees);
            oos.close();
            System.out.println("员工信息已成功写入文件");

            // 4. 从文件读取员工信息
            ObjectInputStream ois = new ObjectInputStream(
                    new FileInputStream(filePath));
            ArrayList<Employee> readEmployees = (ArrayList<Employee>) ois.readObject();
            ois.close();

            // 5. 打印员工信息
            System.out.println("\n从文件读取的员工信息：");
            for (Employee emp : readEmployees) {
                System.out.println(emp);
            }

        } catch (IOException e) {
            System.err.println("文件操作错误：" + e.getMessage());
        } catch (ClassNotFoundException e) {
            System.err.println("类转换错误：" + e.getMessage());
        }
    }
}